<template>
  <div class="supermarket-management">
    <!-- 操作栏 -->
    <div class="operation-bar">
      <el-input
        v-model="searchText"
        placeholder="搜索鲜花名称/编号/类别"
        style="width: 360px"
        clearable
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="success" @click="handleAdd">
        <el-icon><Plus /></el-icon>新增鲜花
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-table 
      :data="filteredProducts" 
      border 
      style="width: 100%"
      header-row-class-name="table-header"
      stripe
      highlight-current-row
    >
      <el-table-column prop="productId" label="鲜花编号" width="130" sortable align="center" />
      <el-table-column prop="productName" label="鲜花名称" width="160" />
      <el-table-column prop="category" label="类别" width="120">
        <template #default="{ row }">
          <el-tag effect="plain" :type="categoryTagType[row.category]">
            {{ row.category }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="售价" width="120" sortable align="center">
        <template #default="{ row }">
          <span style="color: #f56c6c;">¥{{ row.price.toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === 'onSale' ? 'success' : 'info'" effect="light">
            {{ row.status === 'onSale' ? '在售中' : '已下架' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="商品描述" width="180" />
      <el-table-column prop="stock" label="库存" width="100" sortable align="center">
        <template #default="{ row }">
          <span :class="{ 'low-stock': row.stock < 10 }">{{ row.stock }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="publishDate" label="上架日期" width="140" sortable />
      <el-table-column label="操作" width="160" fixed="right" align="center">
        <template #default="{ row }">
          <el-button size="small" type="primary" plain @click="handleEdit(row)">编辑</el-button>
          <el-button
            size="small"
            type="danger"
            plain
            @click="handleDelete(row.productId)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditMode ? '编辑鲜花信息' : '添加新鲜花'"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="鲜花编号" prop="productId">
          <el-input 
            v-model="formData.productId" 
            :disabled="isEditMode"
            placeholder="请输入鲜花编号（如：F1001）"
          />
        </el-form-item>
        <el-form-item label="鲜花名称" prop="productName">
          <el-input 
            v-model="formData.productName"
            placeholder="请输入鲜花名称"
          />
        </el-form-item>
        <el-form-item label="鲜花类别" prop="category">
          <el-select 
            v-model="formData.category"
            placeholder="请选择鲜花类别"
            style="width: 100%"
          >
            <el-option
              v-for="item in categories"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="销售价格" prop="price">
          <el-input-number
            v-model="formData.price"
            :min="0"
            :step="0.1"
            controls-position="right"
            style="width: 100%"
            :precision="2"
            placeholder="请输入销售价格"
          >
            <template #prefix>¥</template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="商品状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio-button label="onSale">在售中</el-radio-button>
            <el-radio-button label="soldOut">已下架</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input 
            type="textarea"
            v-model="formData.description" 
            rows="3"
            placeholder="请输入鲜花描述信息"
            show-word-limit
            maxlength="100"
          />
        </el-form-item>
        <el-form-item label="库存数量" prop="stock">
          <el-input-number
            v-model="formData.stock"
            :min="0"
            :step="1"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="上架日期" prop="publishDate">
          <el-date-picker
            v-model="formData.publishDate"
            type="date"
            placeholder="选择上架日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="success" @click="submitForm"> 确认提交 </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 鲜花类别配置
const categories = [
  '玫瑰系列',
  '百合系列',
  '康乃馨',
  '郁金香',
  '向日葵',
  '满天星',
  '绣球花',
  '混合花束'
]

// 类别标签样式映射
const categoryTagType = {
  '玫瑰系列': 'danger',
  '百合系列': 'success',
  '康乃馨': 'warning',
  '郁金香': '',
  '向日葵': 'info',
  '满天星': 'success',
  '绣球花': 'warning',
  '混合花束': 'danger'
}

// 鲜花数据（10条）
const products = ref([
  {
    productId: 'F1001',
    productName: '红玫瑰花束',
    category: '玫瑰系列',
    price: 298.0,
    status: 'onSale',
    description: '99朵云南红玫瑰，精美包装',
    stock: 15,
    publishDate: '2024-03-01'
  },
  {
    productId: 'F1002',
    productName: '香水百合礼盒',
    category: '百合系列',
    price: 228.0,
    status: 'onSale',
    description: '进口多头香水百合，香气持久',
    stock: 8,
    publishDate: '2024-03-05'
  },
  {
    productId: 'F1003',
    productName: '康乃馨花篮',
    category: '康乃馨',
    price: 168.0,
    status: 'soldOut',
    description: '粉色康乃馨搭配绿叶，母亲节首选',
    stock: 0,
    publishDate: '2024-02-28'
  },
  {
    productId: 'F1004',
    productName: '郁金香花束',
    category: '郁金香',
    price: 198.0,
    status: 'onSale',
    description: '荷兰进口彩色郁金香',
    stock: 12,
    publishDate: '2024-03-10'
  },
  {
    productId: 'F1005',
    productName: '向日葵花盒',
    category: '向日葵',
    price: 188.0,
    status: 'onSale',
    description: '5支向日葵搭配尤加利叶',
    stock: 3,
    publishDate: '2024-03-12'
  },
  {
    productId: 'F1006',
    productName: '满天星干花',
    category: '满天星',
    price: 128.0,
    status: 'onSale',
    description: '永久保存的蓝色满天星',
    stock: 5,
    publishDate: '2024-03-15'
  },
  {
    productId: 'F1007',
    productName: '绣球花束',
    category: '绣球花',
    price: 258.0,
    status: 'onSale',
    description: '进口蓝色绣球花，婚礼用花',
    stock: 6,
    publishDate: '2024-03-18'
  },
  {
    productId: 'F1008',
    productName: '混合花束',
    category: '混合花束',
    price: 328.0,
    status: 'onSale',
    description: '玫瑰+百合+康乃馨组合',
    stock: 9,
    publishDate: '2024-03-20'
  },
  {
    productId: 'F1009',
    productName: '粉色玫瑰礼盒',
    category: '玫瑰系列',
    price: 268.0,
    status: 'onSale',
    description: '戴安娜粉玫瑰33支，丝带包装',
    stock: 7,
    publishDate: '2024-03-22'
  },
  {
    productId: 'F1010',
    productName: '白百合花篮',
    category: '百合系列',
    price: 358.0,
    status: 'soldOut',
    description: '白色百合搭配文竹，高端花艺',
    stock: 0,
    publishDate: '2024-03-25'
  }
])

// 搜索功能
const searchText = ref('')
const filteredProducts = computed(() => {
  const search = searchText.value.toLowerCase()
  return products.value.filter(product => 
    product.productId.toLowerCase().includes(search) ||
    product.productName.toLowerCase().includes(search) ||
    product.category.toLowerCase().includes(search) ||
    product.description.toLowerCase().includes(search)
  )
})

// 对话框相关状态
const dialogVisible = ref(false)
const isEditMode = ref(false)
const formRef = ref(null)
const formData = reactive({
  productId: '',
  productName: '',
  category: '',
  price: 0,
  status: 'onSale',
  description: '',
  stock: 0,
  publishDate: new Date().toISOString().split('T')[0]
})

// 表单验证规则
const formRules = {
  productId: [
    { required: true, message: '鲜花编号不能为空', trigger: 'blur' },
    { pattern: /^F\d{4}$/, message: '编号格式：F+4位数字', trigger: 'blur' }
  ],
  productName: [
    { required: true, message: '请输入鲜花名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在2到50个字符', trigger: 'blur' }
  ],
  category: { required: true, message: '请选择鲜花类别', trigger: 'change' },
  price: [
    { required: true, message: '请输入销售价格', trigger: 'blur' },
    { type: 'number', min: 0.1, message: '价格必须大于0', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入库存数量', trigger: 'blur' },
    { type: 'number', min: 0, message: '库存不能为负数', trigger: 'blur' }
  ],
  publishDate: { required: true, message: '请选择上架日期', trigger: 'change' }
}

// 处理添加
const handleAdd = () => {
  isEditMode.value = false
  resetForm()
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row) => {
  isEditMode.value = true
  Object.assign(formData, { ...row })
  dialogVisible.value = true
}

// 处理删除
const handleDelete = (productId) => {
  ElMessageBox.confirm('此操作将永久删除该鲜花，是否继续？', '警告', {
    confirmButtonText: '确认删除',
    cancelButtonText: '取消',
    type: 'warning',
    confirmButtonClass: 'el-button--danger'
  }).then(() => {
    products.value = products.value.filter(p => p.productId !== productId)
    ElMessage.success('鲜花删除成功')
  }).catch(() => {})
}

// 提交表单
const submitForm = async () => {
  await formRef.value.validate()
  if (isEditMode.value) {
    const index = products.value.findIndex(p => p.productId === formData.productId)
    products.value.splice(index, 1, { ...formData })
  } else {
    if (products.value.some(p => p.productId === formData.productId)) {
      return ElMessage.warning('鲜花编号已存在，请修改')
    }
    products.value.push({ ...formData })
  }
  dialogVisible.value = false
  ElMessage.success(isEditMode.value ? '鲜花信息已更新' : '新鲜花添加成功')
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    productId: '',
    productName: '',
    category: '',
    price: 0,
    status: 'onSale',
    description: '',
    stock: 0,
    publishDate: new Date().toISOString().split('T')[0]
  })
}
</script>

<style scoped lang="scss">
.supermarket-management {
  padding: 24px;
  background: #f8fafc;
  min-height: 100vh;

  .operation-bar {
    padding: 16px 24px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(28, 36, 56, 0.08);
    margin-bottom: 24px;
    display: flex;
    align-items: center;
    gap: 16px;
  }

  :deep(.table-header) th {
    background-color: #f8fafc !important;
    color: #64748b;
    font-weight: 600;
  }

  .el-table {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(28, 36, 56, 0.08);
    
    .low-stock {
      color: #e6a23c;
      font-weight: 500;
    }
  }

  .el-tag {
    font-size: 13px;
    padding: 0 8px;
    height: 26px;
    line-height: 24px;
  }
}

.el-dialog {
  border-radius: 12px;
  
  .el-dialog__header {
    border-bottom: 1px solid #e2e8f0;
    margin: 0 24px;
    padding: 24px 0 16px;
  }
  
  .el-dialog__body {
    padding: 24px 32px;
  }
  
  .el-dialog__footer {
    border-top: 1px solid #e2e8f0;
    padding: 16px 24px;
  }
}

.el-form-item {
  margin-bottom: 20px;
}
</style>